package com.example.demo.controller;

import com.example.demo.entity.BaseResult;
import com.example.demo.entity.Person;
import com.example.demo.utils.IdGen;
import org.springframework.web.bind.annotation.*;

/**
 * @author 张露晨
 * @date 2017/9/27 15:58.
 */
@RestController
@RequestMapping("/api/person")
public class PersonController {

    /**
     * 新增
     *
     * @param name 姓名
     * @param sex  性别
     * @param age  年龄
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public BaseResult add(@RequestParam(value = "name", required = false) String name,
                          @RequestParam(value = "sex") String sex,
                          @RequestParam(value = "age") Integer age) {
        Person p = new Person();
        p.setId(IdGen.uuid());
        p.setName(name);
        p.setAge(age);
        p.setSex(sex);
        boolean result = p.insert();
        if (!result) {
            return new BaseResult(400, "保存失败！");
        }
        return new BaseResult(200, "保存成功！");
    }

    /**
     * 修改
     *
     * @param id   主键
     * @param name 姓名
     * @param sex  性别
     * @param age  年龄
     * @return
     */
    @PostMapping("/update")
    public BaseResult update(@RequestParam(value = "id") String id,
                             @RequestParam(value = "name", required = false) String name,
                             @RequestParam(value = "sex", required = false) String sex,
                             @RequestParam(value = "age", required = false) Integer age) {
        Person person = new Person().selectById(id);
        if (null == person) {
            return new BaseResult(400, "修改失败！");
        }
        if (null != name && "" != name) {
            person.setName(name);
        }
        if (null != sex && "" != sex) {
            person.setSex(sex);
        }
        if (null != age) {
            person.setAge(age);
        }
        boolean result = person.updateById();
        if (!result) {
            return new BaseResult(400, "更新失败！");
        }
        return new BaseResult(200, "更新成功！");
    }

    /**
     * 查询
     *
     * @param id 主键
     * @return
     */
    @PostMapping("/select")
    public BaseResult select(@RequestParam(value = "id") String id) {
        return new BaseResult(200, "查询成功！", new Person().selectById(id));
    }

    /**
     * 删除
     *
     * @param id 主键
     * @return
     */
    @PostMapping("/delete")
    public BaseResult delete(@RequestParam(value = "id") String id) {
        boolean result = new Person().deleteById(id);
        if (!result) {
            return new BaseResult(400, "删除失败！");
        }
        return new BaseResult(200, "删除成功！", new Person().selectById(id));
    }

}
